package com.tronsis.distribution.fragment.material;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageAndVideoPreviewSeeActivity;
import com.tronsis.distribution.R;
import com.tronsis.distribution.activity.material.UploadMaterialActivity;
import com.tronsis.distribution.bean.ResourceBean;
import com.tronsis.distribution.biz.factory.ResourceBizFactory;
import com.tronsis.distribution.eventbus.EventMessage;
import com.tronsis.distribution.eventbus.EventTag;
import com.tronsis.distribution.http.Url;
import com.tronsis.distribution.util.CommonUtil;
import com.tronsis.distribution.util.GlideImageLoader;
import com.tronsis.distribution.util.StateUtil;
import com.tronsis.library.adapter.recyclerview.CommonAdapter;
import com.tronsis.library.adapter.recyclerview.base.ViewHolder;
import com.tronsis.library.adapter.recyclerview.wrapper.LoadMoreWrapper;
import com.tronsis.library.fragment.BaseFragment;
import com.tronsis.library.http.ListBean;
import com.tronsis.library.http.UICallBack;
import com.tronsis.library.imageloader.ImageLoader;
import com.tronsis.library.util.DateUtil;
import com.tronsis.library.util.DisplayUtil;
import com.tronsis.library.util.LogUtil;
import com.tronsis.library.util.SRFConfigUtil;
import com.tronsis.library.util.StringUtil;
import com.tronsis.library.util.ToastUtil;
import com.tronsis.library.widget.ConfirmDialog;
import com.tronsis.library.widget.MyDecoration;
import com.tronsis.library.widget.RecycleViewDivider;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.lzy.imagepicker.ImagePicker.REQUEST_CODE_PREVIEW;

/**
 * @author scofield@tronsis.com
 * @date 2019/3/13 15:58
 */
public class MyMaterialFragment extends BaseFragment {

    @BindView(R.id.srl_material)
    SwipeRefreshLayout mSrl;
    @BindView(R.id.rv_material)
    RecyclerView mRvMaterial;

    private CommonAdapter<ResourceBean> mAdapter;
    private List<ResourceBean> mMaterialList = new ArrayList<>();

    private LoadMoreWrapper mLoadMoreWrapper;
    private int mPage = 1;
    private int mSize = 15;
    private int mTotal;
    private String mTypeId;
    private String mSearch;

    @Override
    protected View onCreateView() {
        View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_category, null);
        ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void initData() {
        Bundle bundle = getArguments();
        mTypeId = bundle.getString("typeId");

        initRv();
        httpGetResource(1, mSize, true);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventMessage message) {
        switch (message.getTag()) {
            case EventTag.MATERIAL_SEARCH_ME:
                mSearch = (String) message.getParams();
                httpGetResource(1, mSize, true);
                break;
            case EventTag.MATERIAL_REFRESH_ME:
                String typyId = (String) message.getParams();
                if (StringUtil.isEquals(mTypeId, typyId) || mTypeId == null) {
                    httpGetResource(1, mSize, true);
                }
                break;
            default:
                break;
        }
    }

    private void initRv() {
        ImagePicker.getInstance().setImageLoader(new GlideImageLoader());
        SRFConfigUtil.initSwipeRefreshLayout(mSrl);
        mSrl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                httpGetResource(1, mSize, true);
            }
        });


        mAdapter = new CommonAdapter<ResourceBean>(getContext(), mMaterialList, R.layout.item_my_material) {
            @Override
            protected void convert(final ViewHolder holder, final ResourceBean resourceBean, final int position) {
                holder.setText(R.id.tv_state, StateUtil.getResSate(mContext, resourceBean.getState()));
                holder.setText(R.id.tv_date, DateUtil.getDateTimeString(resourceBean.getCreatedOn()));
                holder.setText(R.id.tv_content, resourceBean.getContent());
                holder.setText(R.id.tv_type, getString(R.string.format_type, resourceBean.getTypeName()));

                final String videoFid = resourceBean.getVideoFid();
                final String imageFid = resourceBean.getImageFid();

                RecyclerView rv = holder.getView(R.id.rv_image);
                ArrayList<ImageItem> allList = new ArrayList<>();
                if (!TextUtils.isEmpty(videoFid)) {
                    ImageItem imageItem = new ImageItem();
                    imageItem.url = Url.FILE_DOWNLOAD + resourceBean.getVideoFid();
                    imageItem.isVideo = true;
                    allList.add(imageItem);
                }
                ArrayList<ImageItem> splitImage = CommonUtil.getSplitImage(imageFid);
                allList.addAll(splitImage);
                setImageRv(rv, allList,videoFid);

                TextView tvEdit = holder.getView(R.id.tv_edit);
                TextView tvDelete = holder.getView(R.id.tv_delete);
                tvEdit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(mContext, UploadMaterialActivity.class);
                        intent.putExtra("ResourceBean", mMaterialList.get(position));
                        startActivity(intent);
                    }
                });
                tvDelete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showDeleteDialog(holder.getLayoutPosition(), resourceBean);
                    }
                });
                if (StringUtil.isEquals(resourceBean.getState(), StateUtil.RES_VERIFY)) {
                    tvEdit.setVisibility(View.GONE);
                } else {
                    tvEdit.setVisibility(View.VISIBLE);
                }

            }

            private void setImageRv(RecyclerView mRvUserUpload, final ArrayList<ImageItem> mImageList, String videoFid) {
                CommonAdapter mCustomImageAdapter = new CommonAdapter<ImageItem>(mContext, mImageList, R.layout.item_image_material) {
                    @Override
                    protected void convert(final ViewHolder holder, final ImageItem imageItem, final int position) {
                        ImageView ivItem = holder.getView(R.id.iv_item);
                        ImageView ivVideo = holder.getView(R.id.iv_video);
                        if (imageItem.isVideo) {
                            ivItem.setVisibility(View.GONE);
                            ivVideo.setVisibility(View.VISIBLE);
                            ivVideo.setImageResource(R.drawable.icon_video_play);
                            ivVideo.setScaleType(ImageView.ScaleType.CENTER);
                        } else {
                            ivItem.setVisibility(View.VISIBLE);
                            ivVideo.setVisibility(View.GONE);
                            ivItem.setScaleType(ImageView.ScaleType.CENTER_CROP);
                            ivItem.setImageResource(R.color.transparent);
                            ivItem.setBackgroundResource(R.color.transparent);
                            ImageLoader.display(mContext, imageItem.url, ivItem);
                        }

                        ivItem.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intentPreview = new Intent(getContext(), ImageAndVideoPreviewSeeActivity.class);
                                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                                intentPreview.putParcelableArrayListExtra(ImagePicker.EXTRA_IMAGE_ITEMS, mImageList);
                                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                            }
                        });
                        ivVideo.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intentPreview = new Intent(getContext(), ImageAndVideoPreviewSeeActivity.class);
                                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                                intentPreview.putParcelableArrayListExtra(ImagePicker.EXTRA_IMAGE_ITEMS, mImageList);
                                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                            }
                        });
                    }
                };

                if (!TextUtils.isEmpty(videoFid)) {
                    mRvUserUpload.setLayoutManager(new LinearLayoutManager(mContext));
                } else {
                    mRvUserUpload.setLayoutManager(new GridLayoutManager(mContext, 3, LinearLayoutManager.VERTICAL, false) {
                        @Override
                        public boolean canScrollVertically() {
                            return false;
                        }
                    });
                }
                mRvUserUpload.setAdapter(mCustomImageAdapter);
            }
        };


        mLoadMoreWrapper = new LoadMoreWrapper(mAdapter);
        mLoadMoreWrapper.setLoadMoreView(R.layout.rv_load_more);
        mLoadMoreWrapper.setOnLoadMoreListener(new LoadMoreWrapper.OnLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                if (mMaterialList.size() % 15 == 0 && mMaterialList.size() > 0 && mMaterialList.size() < mTotal) {
                    mPage = (mMaterialList.size() / 15) + 1;
                    httpGetResource(mPage, mSize, false);
                }
            }
        });
        int height = DisplayUtil.getInstance(getContext()).dp2px(14);
        int color = Color.parseColor("#F4F4F4");
        RecycleViewDivider decoration = new RecycleViewDivider(getContext(), MyDecoration.VERTICAL_LIST, height, color);
        mRvMaterial.addItemDecoration(decoration);
        mRvMaterial.setLayoutManager(new LinearLayoutManager(getContext()));
        mRvMaterial.setAdapter(mLoadMoreWrapper);
    }


    private void showDeleteDialog(final int position, final ResourceBean resourceBean) {
        ConfirmDialog dialog = new ConfirmDialog(mContext, new ConfirmDialog.OnBottomButtonClickListener() {
            @Override
            public void onLeftButtonClick(View view) {

            }

            @Override
            public void onRightButtonClick(View view) {
                httpDeleteResource(position, resourceBean);

            }
        });
        dialog.showDialog("确认删除？", "取消", "确定");
    }


    private void httpGetResource(int page, int size, final boolean isRefresh) {
        try {
            LogUtil.e("MyMaterialFragment-http", "typeId = " + mTypeId);

            ResourceBizFactory.createBiz().getResource(getActivity(), true, page, mSearch, size, mTypeId, new UICallBack() {
                @Override
                public void onStart() {
                    if (isRefresh) {
                        mSrl.setRefreshing(true);
                    }
                }

                @Override
                public void onRefresh(Object data) {
                    mSrl.setRefreshing(false);
                    ListBean listBean = (ListBean) data;
                    mTotal = listBean.getTotal();
                    List<ResourceBean> list = listBean.getList();
                    if (isRefresh) {
                        mMaterialList.clear();
                        mMaterialList.addAll(list);
                    } else {
                        mMaterialList.addAll(list);
                    }
                    mLoadMoreWrapper.notifyDataSetChanged();
                }

                @Override
                public void onFailure(int status) {
                    mSrl.setRefreshing(false);

                }
            });
        } catch (Exception e) {
            mSrl.setRefreshing(false);
            e.printStackTrace();
        }
    }

    private void httpDeleteResource(final int position, final ResourceBean resourceBean) {
        try {
            ResourceBizFactory.createBiz().deleteResource(getActivity(), resourceBean.getId(), new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    dismissLoadingDialog();
                    ToastUtil.showMessage(mContext, "已删除");
                    mLoadMoreWrapper.notifyItemRemoved(position);
                    mMaterialList.remove(position);
                    EventBus.getDefault().post(new EventMessage(EventTag.MATERIAL_REFRESH_ME, resourceBean.getTypeId()));
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();

                }
            });
        } catch (Exception e) {
            dismissLoadingDialog();
            e.printStackTrace();
        }
    }
}
